package com.shenganyuan.smac.common.utils;

import android.util.Log;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 *
 * Created by pzlvm on 2016/7/1.
 */
public class GsonUtil {


    /**
     * 使用Gson解析json结果
     */
    public static  <T> T gsonModelFrom(Class<T> clazz, String prefix) {
        try {
            Gson gson = new Gson();
            T obj = gson.fromJson(prefix, clazz);
            return obj;
        }catch (Throwable ex){
            Log.e("gsonModelFrom",ex.toString());
            return null;
        }
    }

    /**
     * 解析json列表
     */
    public static  <T> ArrayList<T> gsonModelArrayFrom(String prefix) {
        try {
            Gson gson = new Gson();
            Type type = new TypeToken<ArrayList<T>>() {}.getType();
            ArrayList<T> obj = gson.fromJson(prefix, type);
            return obj;
        }catch (Throwable ex){
            Log.e("gsonModelFrom",ex.toString());
            return null;
        }
    }

    /**
     * 转换成jsonString
     */
    public static String gsonObject2JsonStr(Object bean){
        try{
            Gson gson = new Gson();
            return gson.toJson(bean);
        }catch (Throwable ex){
            return "";
        }
    }

    public static <T>T gsonStr2Object(String str, Class<T> tClass){
        try{
            return new Gson().fromJson(str,tClass);
        }catch (Throwable ex){
            return null;
        }
    }

    /**
     * 将map生成jsonString
     */
    public static String jsonMapToJsonString(HashMap map){
        try{
            JSONArray jmap = new JSONArray();
            jmap.put(map);
            return jmap.toString();
        }catch (Throwable ex){
            return "";
        }
    }

    // Json生成Map
    public Map<String, Object> jsonToMap(String jsonString) throws JSONException {
        //JSONObject必须以"{"开头
        JSONObject jsonObject = new JSONObject(jsonString);
        Map<String, Object> resultMap = new HashMap<>();
        Iterator<String> iter = jsonObject.keys();
        String key;
        Object value;
        while (iter.hasNext()) {
            key = iter.next();
            value = jsonObject.get(key);
            resultMap.put(key, value);
        }
        return resultMap;
    }

}
